import React from 'react';
import { ElementClass } from 'breeze-leaf-core-lib';
import { getComponent } from './componentManager';
import { anyObject, RootProps } from '../interface/state';
import { PropAndBindingClass } from 'breeze-leaf-core-lib/dist/components/PropAndBindingClass';
import { getComponentPropProxy } from '../factory';
import { propsParse } from '../utils/propsParse';
import { get } from 'lodash';

export const viewComponent = (view: ElementClass, reduxProps: RootProps) => {
  if (!view.name) {
    return null;
  }

  const View = getComponent(view.name);

  if (!View) {
    window.console.error(`${view.name} is not found!`)
    return null;
  }

  let props = view.getProps()?.reduce(
    (ps: anyObject, prop: PropAndBindingClass) => {
      prop && (ps[prop.field] = prop.value);
      return ps;
    }, {}) || {};
  props = view.getBindings()?.reduce(
    (bs: anyObject, prop: PropAndBindingClass) => {
      prop && (bs[prop.field] = get(reduxProps, prop.value));
      return bs;
    }, props) || props;

  const proxyProps = getComponentPropProxy(view.name, view)

  const children = view.getChildren();

  return (
    <View {...propsParse(props, view.name)} {...proxyProps}>
      {
        children && (children.length > 1
          ? children.map(child => {
            return <React.Fragment key={child.uuid}>{viewComponent(child, reduxProps)}</React.Fragment>;
          })
          : children[0] && viewComponent(children[0], reduxProps))
        || null
      }
    </View>
  );
}